﻿using System;
using System.IO;
using System.Linq;


namespace DiverseStudents.Mods
{
    internal class ModCreate
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        const int length = 7;
        readonly static Random random;
         static ModCreate()
        {
            random = new Random();
        }

        public (bool, ModArchive) New()
        {
            ModArchive mod = new ModArchive();
            if (DConfig.CheckLoadPath())
            {
                string name = GetFileName();
                var modPath = Path.Combine(DConfig.savePath, name);
                if (Directory.Exists(modPath))//发生碰撞
                {
                    name = GetFileName();
                    modPath = Path.Combine(DConfig.savePath, name);
                }
                if (!CreateModPath(modPath))
                {
                    return (false, mod);
                }
                mod.id = name;
                mod.check = true;
                mod.hasImage = false;
                return (true, mod);
            }
            else
            {
                return (false, mod);
            }

        }

        public static string GetFileName()
        {
            return "Mod_" + new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
        }

        private bool CreateModPath(string path)
        {
            var dir = Directory.CreateDirectory(path);
            if (!dir.Exists) { return false; }
            dir = Directory.CreateDirectory(Path.Combine(path, "Cfgs"));
            if (!dir.Exists) { return false; }
            dir = Directory.CreateDirectory(Path.Combine(path, "Resoures"));
            if (!dir.Exists) { return false; }
            dir = Directory.CreateDirectory(Path.Combine(path, "Plugins"));
            if (!dir.Exists) { return false; }
            return true;
        }

    
    }
}
